package filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommentFilter implements Filter {

	/**
	 * 释放资源的方法，在servlet容器删除Filter对象之前执行。
	 * 
	 */
	public void destroy() {

	}

	/**
	 * servlet容器在调用servlet之前，会先执行该 方法。servlet容器会将构造好的HttpSevletRequest,
	 * HttpServletResponse对象作为参数传递给该方法。
	 * FilterChain.doFilter(ServletRequest,ServletResponse)
	 * 其作用是调用后续的过滤器或者servlet。
	 */
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		PrintWriter out = response.getWriter();
		String content = request.getParameter("content");
		if (content.indexOf("dogff") != -1) {
			out.println("illegal comment!");
			return;
		}
		arg2.doFilter(request, response);
	}

	/**
	 * 初始化方法，servlet容器在创建好Filter实例之后， 会调用该方法，执行初始化操作（获得资源）。
	 * 可以通过FilterConfig对象（也是由servlet容器创建的） 获得初始化参数。
	 */
	public void init(FilterConfig arg0) throws ServletException {

	}

}
